<template>
  <div class="payer-account">
    <div
      v-for="(account, index) in checkedPayerAccount"
      :key="account.index"
      class="sale-accounteeParty-div"
      :class="{ readonly: readonly }"
    >
      <template v-if="readonly">
        <span>
          {{
            account.payerAccount.accountBank
              ? account.payerAccount.accountBank +
                account.payerAccount.accountNumber +
                $t('【') +
                account.payerAccount.accountName +
                $t('】')
              : ''
          }}
        </span>
      </template>
      <el-select
        v-else
        v-model="account.payerAccount"
        filterable
        style="margin-left: 12px; flex: 1"
        value-key="bankCardUniqueness"
        clearable
        :placeholder="parameter.promptTemplate"
        :disabled="!currency || readonly"
        @change="changeData(index, $event)"
      >
        <el-option
          v-for="item in getBankCardData(
            account.accounteePartyBankList,
            'payerAccount',
            index
          )"
          :key="item.bankCardUniqueness"
          :label="
            item.accountBank +
            item.accountNumber +
            $t('【') +
            item.accountName +
            $t('】')
          "
          :value="item"
        >
        </el-option>
      </el-select>
      <span>{{ bankGetAccount(index) }}</span>
    </div>
  </div>
</template>
<script>
import eventBus from '@/assets/utils/eventBus.js'
export default {
  name: 'payerAccount',
  props: {
    detail: {
      typr: Object,
      default: () => {
        return {}
      },
    },
    currentForm: {
      typr: Object,
      default: () => {
        return {}
      },
    },
    value: [Object, String, Array],
    disabled: Boolean,
    parameter: {
      typr: Object,
      default: () => {
        return {}
      },
    },
  },

  data() {
    let vm = this
    return {
      checkedPayerAccount: [
        {
          index: new Date().getTime(),
          payerAccount: {},
          accounteePartyBankList: [],
        },
      ],

      checkedData: [],
      checkedAccounteeParty: [],
      currency: null,
      isInit: true,
      rules: {
        payerAccount: [
          {
            required: this.parameter.state === 4,
            validator: (rule, value, callback) => {
              //首次塞值，不知道为啥，始终没有重新触发trigger，所以第一次塞值的时候，不让校验
              if (
                vm.isInit &&
                vm.value &&
                vm.checkedPayerAccount.length == 1 &&
                !vm.checkedPayerAccount[0].payerAccount.accountNumber
              ) {
                callback()
                return
              }
              if (this.parameter.state != 4 && this.parameter.fillFlag != 0) {
                callback()
                return
              }
              debugger
              if (vm.checkedPayerAccount) {
                let error = null
                vm.checkedPayerAccount.forEach((it) => {
                  if (error) {
                    return
                  }
                  if (!it.payerAccount.accountNumber) {
                    error = this.$t('请选择付款方账户')
                  }
                })
                if (error) {
                  callback(new Error(error))
                } else {
                  callback()
                }
              } else {
                callback(new Error(this.$t('请选择付款方账户')))
                return
              }
            },
            trigger: 'change',
            type: 'array',
          },
        ],
      },
      readonly: false,
    }
  },
  created() {
    let vm = this
    this.initValue = this.value
    this.readonly = Boolean(this.$route.query.readonly) || this.disabled
    //接收客户主数据的第一次添加
    eventBus.$on('changeaccount', (parameter, data, index) => {
      //必须是抬头信息的塞到抬头信息里面，支付条款的塞到支付条款里面
      if (
        parameter.parameterPosition !== vm.parameter.parameterPosition ||
        vm.$route.query.readonly
      ) {
        return
      }
      if (parameter.parameterNumber === 'accounteeParty') {
        if (data.length < vm.checkedPayerAccount.length) {
          vm.checkedPayerAccount.splice(index, 1)
          return
        }
        data.forEach((it, i) => {
          let list = it.accounteeParty
            ? it.accounteeParty.bankCardResults ||
              it.accounteeParty.bankCardInfos ||
              []
            : [] //获取选择数据的银行卡数组
          // if(vm.isInit){
          //     vm.isInit = false;
          //     return;
          // }
          if (vm.checkedPayerAccount[i]) {
            let partyCode = vm.checkedPayerAccount[i].payerAccount.partyCode
            let payerAccount =
              partyCode === it.accounteeParty.code
                ? vm.checkedPayerAccount[i].payerAccount
                : {}
            let hasChekced = list.find(
              (item) =>
                item.accountNumber + vm.currency ===
                payerAccount.bankCardUniqueness
            )
            vm.$set(vm.checkedPayerAccount, i, {
              ...vm.checkedPayerAccount[i],
              payerAccount: hasChekced ? payerAccount : {},
              accounteePartyBankList: list,
            })
            this.$emit('input', vm.checkedPayerAccount)
          } else {
            vm.checkedPayerAccount.push({
              index: new Date().getTime(),
              payerAccount: {},
              accounteePartyBankList: list,
            })
          }
        })
        vm.checkedAccounteeParty = data
      }
    })
    eventBus.$on('changeCurrency', (parameter, data) => {
      // //必须是抬头信息的塞到抬头信息里面，支付条款的塞到支付条款里面
      if (
        parameter.parameterPosition &&
        parameter.parameterPosition !== vm.parameter.parameterPosition
      ) {
        return
      }
      vm.currency = data
      //因为bankCardUniqueness必须取到currency，所以将塞值放在currency的变化里面
      if (
        vm.isInit &&
        vm.initValue &&
        vm.checkedPayerAccount.length == 1 &&
        !vm.checkedPayerAccount[0].payerAccount.accountNumber
      ) {
        vm.checkedData = JSON.parse(vm.initValue) || []
        if (vm.checkedData && vm.checkedData.length > 0) {
          let arr = []
          arr = vm.checkedData.map((it) => {
            let obj = {
              index: new Date().getTime(),
              payerAccount: it
                ? {
                    ...it,
                    bankCardUniqueness: it.accountNumber + vm.currency,
                  }
                : {},
              accounteePartyBankList: vm.$route.query.readonly
                ? [
                    {
                      ...it,
                      bankCardUniqueness: it.accountNumber + vm.currency,
                    },
                  ]
                : [],
            }
            vm.getBankCardData(obj.accounteePartyBankList)
            return obj
          })
          vm.$set(vm, 'checkedPayerAccount', arr)
          vm.$emit('input', vm.checkedPayerAccount)
        }
      } else {
        this.checkedPayerAccount.forEach((it) => {
          it.payerAccount = {}
        })
      }
      // vm.checkedPayerAccount.forEach(it => {
      //     vm.getBankCardData(it.accounteePartyBankList)
      // })
      vm.$nextTick(() => {
        vm.isInit = false
      })
    })
    this.$emit('setrules', this.parameter, {
      [this.parameter.parameterNumber]: this.rules.payerAccount,
    })
  },
  methods: {
    getBankCardData(list, name, index) {
      if (!list) {
        list = []
      }
      let obj = {
        1: 'CNY',
        2: 'USD',
      }
      let newarr = list
        .filter((it) => {
          return (
            !this.currency ||
            (it.currency &&
              (it.currency.indexOf(this.currency + '') != -1 ||
                it.currency.indexOf(obj[this.currency]) != -1))
          )
        })
        .map((it) => {
          return {
            ...it,
            bankCardUniqueness: it.accountNumber + this.currency,
          }
        })
      // this.clearBankData(newarr, name, index);
      return newarr
    },
    bankGetAccount(index) {
      let text = ''
      if (this.checkedAccounteeParty.length) {
        if (
          (index || index == 0) &&
          this.checkedAccounteeParty[index] &&
          this.checkedAccounteeParty[index].accounteeParty
        ) {
          text =
            (this.checkedAccounteeParty[index].accounteeParty.code || '') +
            (this.checkedAccounteeParty[index].accounteeParty.fullName || '')
        }
      }
      return text
    },
    changeData(index, val) {
      if (val) {
        if (this.checkedPayerAccount[index]) {
          this.checkedPayerAccount[index].payerAccount.partyCode =
            this.checkedAccounteeParty[index].accounteeParty.code
        }
        this.$emit('input', this.checkedPayerAccount)
      } else {
        this.$emit('input', '')
      }
    },
    getData() {
      if (
        this.checkedPayerAccount.length > 0 &&
        this.checkedPayerAccount[0].payerAccount.accountNumber
      ) {
        return this.checkedPayerAccount.map((it, index) => {
          return {
            accountBank: it.payerAccount.accountBank,
            accountNumber: it.payerAccount.accountNumber,
            accountName: it.payerAccount.accountName,
            partyCode: this.checkedAccounteeParty[index].accounteeParty.code,
          }
        })
      } else {
        return []
      }
    },
  },
}
</script>
<style lang="scss">
.payer-account {
  .sale-accounteeParty-div {
    display: flex;
    margin-bottom: 12px;
    &.readonly {
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #333;
      padding: 0px 15px;
      height: 32px;
    }
    .el-icon-remove {
      font-size: 24px;
      cursor: pointer;
      align-self: center;
      margin-left: 8px;
    }
    &:last-child {
      margin-bottom: 0px;
    }
  }
}
</style>
